package com.itbaizhan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/*获取HttpSession对象*/
/*HttpSession对象的使用
session.setAttribute("key",value)
将数据存储到HttpSession对象中

Object value = session.getAttribute("key")
根据key获取HttpSession中的数据，返回Object

Enumeration attributeNames = session.getAttributeNames()
获取HttpSession中所有的key，返回枚举类型

session.removeAttribute("key")
根据key删除HttpSession中的数据

String id = session.getId()
根据获取当前HttpSession的SessionID，返回字符串类型*/

/*不同的浏览器创建不同的jsessionid,不同的HttpSession对象，所以在A浏览器中的数据，
* 在B的浏览器不可以获取*/
public class GetHttpSessionDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取HttpSession对象
        HttpSession session = req.getSession();
        //获取数据 getAttribute() 是Object类型，要强转
       // String value =(String) session.getAttribute("key");

        //获取HttpSession中所有的key，返回枚举类型
        Enumeration<String>  attributeNames = session.getAttributeNames();

        //设置响应编码
        resp.setContentType("text/plain;charset=utf-8");

        //响应给客户端浏览器
        PrintWriter pw = resp.getWriter();
        //pw.println(value);
        while (attributeNames.hasMoreElements()){
            String key = attributeNames.nextElement();
            String value =(String) session.getAttribute(key);
            pw.println("name: "+key+" value: "+value);
        }
        pw.flush();
        pw.close();
    }
}
